package org.joy;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.shiro.codec.Hex;

public class Main {
    static String accessKey = "1af1555a15c952166a8cb899179bd74f93c17776";
    static String secretKey = "2kNPUz7QpNAC2CyTlB9EK4qS7986jyCKdK+o0Zyv8co=";

    private static byte[] hmacSHA256(byte[] key, String data) throws UnsupportedEncodingException, InvalidKeyException,
            NoSuchAlgorithmException {

        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes());
    }


    private static byte[] getSignatureKey(String key, String date, String regionName, String serviceName)
            throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {

        byte[] kSecret = ("AWS4" + key).getBytes("UTF-8");

        byte[] kDate = hmacSHA256(kSecret, date);

        byte[] kRegion = hmacSHA256(kDate, regionName);

        byte[] kService = hmacSHA256(kRegion, serviceName);
        return hmacSHA256(kService, "aws4_request");
    }



    public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, IOException {

        String context = BaseUtils.readFile("D:\\projects\\s3demo\\policy.json");
        String stringToSign = BaseUtils.encodeBASE64(context);
        System.out.println(stringToSign);

        String accessSecretKey = secretKey;
        String date = "20130524";
        String region = "us-east-1";
        String regionService = "s3";

        byte[] signatureKey = getSignatureKey(accessSecretKey, date, region, regionService);

        byte[] signature = hmacSHA256(signatureKey, stringToSign);

        System.out.println(stringToSign);
        System.out.println(Hex.encodeToString(signature));

    }
}
